【LeetCode 19】Remove Nth Node From End of List 删除链表的倒数第N个节点


“The Linux philosophy is “Laugh in the face of danger”.Oops.Wrong One. “Do it yourself”. Yes, that”s it.”
Linux的哲学就是“在危险面前放声大笑”,呵呵,不是这句,应该是“一切靠自己,自力更生”才对。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
*
* 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
* 一趟扫描
* 两个指针,一个先走n步,然后两个指针同时走,第一个指针到末尾,第二个指针的位置就是倒数第n个节点
*
*/

public class leetcode19 {

public ListNode removeNthFromEnd (ListNode head, int n) {
ListNode i = head, j = head;
for (int k = 0; k < n; k++) {
j = j.next;
}
ListNode temp = i;
while (j != null) {
j = j.next;
temp = i;
i = i.next;
}
if (temp == i) {
head = head.next;
return head;
} else {
temp.next = i.next;
i.next = null;
}
return head;
}
}
Thanks!